package com.yjhb.android.sbz.activity;

import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jojo.android.zxlib.tool.ZxDataTool;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.dialog.BindAliDialog;
import com.yjhb.android.sbz.dialog.BindWxDialog;
import com.yjhb.android.sbz.dialog.InputDialog;
import com.yjhb.android.sbz.entity.Order;
import com.yjhb.android.sbz.mvp.withdrawal.WithdrawalPresenter;
import com.yjhb.android.sbz.mvp.withdrawal.WithdrawalView;
import com.yjhb.android.sbz.tool.CommonDialogCollect;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.MiniLoadingView;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.yjhb.android.sbz.v2.activity.V2BindAliPayActivity;
import com.yjhb.android.sbz.v2.activity.V2BindRealNameActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2020/12/3 9:58
 */
public class WithdrawalActivity extends BaseActivity<WithdrawalPresenter> implements WithdrawalView {
    private final String TAG = "RewardWithdrawalActivity";

    @BindView(R.id.title_tv)
    TextView title_tv;

    @BindView(R.id.zfb_account_layout)
    View zfb_account_layout;
    @BindView(R.id.zfb_account_tv)
    TextView zfb_account_tv;
    @BindView(R.id.zfb_account_change)
    TextView zfb_account_change;
    @BindView(R.id.name_layout)
    View name_layout;
    @BindView(R.id.name_tv)
    TextView name_tv;
    @BindView(R.id.wx_layout)
    View wx_layout;
    @BindView(R.id.zfb_layout)
    View zfb_layout;


    @BindView(R.id.money_et)
    EditText money_et;
    @BindView(R.id.tips_tv)
    TextView tips_tv;
    @BindView(R.id.loading_view)
    MiniLoadingView loading_view;
    @BindView(R.id.content_layout)
    View content_layout;

    ILoading loadingDialog;
    View selectedType;

    private int type;  //提现类型   1赚取金2充值金3保证金


    @Override
    protected boolean isCheckLogin() {
        return true;
    }

    @Override
    protected WithdrawalPresenter initPresenter() {
        return new WithdrawalPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reward_withdrawal;
    }

    @Override
    protected void initUI() {
        type = getIntent().getIntExtra("type", 1);
        loadingDialog = LoadingDialogTool.createDialog(this);
        selectedType = rootView.findViewWithTag("zfb");
        onSelectedType(selectedType);

    }

    @Override
    protected void initData() {
        presenter.specifyConfig(type);
    }

    @Override
    protected void regEvent() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(EventMsg msg) {
        if (msg.msg == EventMsg.USER_UPDATE_OK) {
            refresh();
        }
    }

    @Override
    public void refresh() {
        String balance = "0.00";
        switch (type) {
            case 1:
                title_tv.setText("任务金额");
                tips_tv.setText("提现提醒：\n" +
                        "1、任务金额提现免手续费。\n" +
                        "2、单次提现金额限1000元以内。\n" +
                        "3、24小时内到账，每天可提现一次。");
                balance = App.userInfo.getEarnMoney();
                break;
            case 2:
                title_tv.setText("悬赏余额");
                tips_tv.setText("提现提醒：\n" +
                        "1、赏金提现手续费收取3%。\n" +
                        "2、24小时内到账，每天可提现一次。");
                balance = App.userInfo.getPayMoney();
                break;
            case 3:
                title_tv.setText("保证金");
                balance = App.userInfo.getCreditMoney();
                tips_tv.setText("");
                break;
        }
        if (TextUtils.isEmpty(App.userInfo.getZfbName())) {
            name_tv.setText("真实姓名:未实名");
        } else {
            name_tv.setText("真实姓名:" + App.userInfo.getZfbName());
        }
        if (selectedType.getId() == R.id.zfb_layout) {
            zfb_account_layout.setVisibility(View.VISIBLE);
            name_layout.setVisibility(View.VISIBLE);
            money_et.setHint("请输入提现金额，1元起提（余额：" + balance + "元）");
            String zfb = App.userInfo.getZfbAccount();
            if (TextUtils.isEmpty(zfb)) {
                zfb = "未绑定";
                zfb_account_change.setVisibility(View.GONE);
                name_layout.setVisibility(View.GONE);
            } else {
                zfb_account_change.setVisibility(View.VISIBLE);
                name_layout.setVisibility(View.VISIBLE);
            }
            zfb_account_tv.setText("支付宝账号:" + zfb);
        } else if (selectedType.getId() == R.id.wx_layout) {
            zfb_account_layout.setVisibility(View.GONE);
            name_layout.setVisibility(View.VISIBLE);
            money_et.setHint("请输入提现金额，" + (type == 2 ? "1" : "1") + "元起提（余额：" + balance + "元）");
        }
    }


    @OnClick(R.id.back)
    public void back() {
        finish();
    }


    @OnClick({R.id.wx_layout, R.id.zfb_layout})
    public void onSelectedType(View view) {
        if (selectedType != null) {
            selectedType.setSelected(false);
        }
        selectedType = view;
        selectedType.setSelected(true);
        refresh();
    }

    @OnClick(R.id.zfb_account_change)
    void change() {
        InputDialog inputDialog = new InputDialog(this);
        inputDialog.setTitleText("更换支付宝账号");
        inputDialog.getInputView().setInputType(InputType.TYPE_CLASS_TEXT);
        inputDialog.setTipsText("只能更改支付宝账号，不能更改姓名，支付宝账号必须属于该姓名，每年最多更改3次。" +
                "\n已绑定的姓名：" + App.userInfo.getZfbName());
        inputDialog.setOnClickListener(new InputDialog.OnClickListener() {
            @Override
            public void onClick(int button) {
                if (button == InputDialog.BUTTON_SUBMIT) {
                    if (TextUtils.isEmpty(Tool.getText(inputDialog.getInputView()))) {
                        ZxToast.showINFOBottomToast("请先填写新的支付宝账号");
                        return;
                    }
                    if (!verifyZfb(Tool.getText(inputDialog.getInputView()))){
                        ZxToast.showINFOBottomToast("请填写正确的支付宝账号");
                        return;
                    }
                    presenter.changeZfb(Tool.getText(inputDialog.getInputView()));
                }
                inputDialog.dismiss();
            }
        });
        inputDialog.getInputView().setHint("请输入新的支付宝账号");
        inputDialog.show();
    }

    @OnClick(R.id.withdraw_tv)
    public void withdraw_tv() {
        if (Tool.isEditEmpty(money_et)) {
            ZxToast.showBottomToastLight("请输入提现金额。");
            return;
        }
        if (TextUtils.isEmpty(App.userInfo.getPhone())) {
            ZxToast.showINFOBottomToast("请先绑定手机号哦！");
            ZxActivityTool.skipActivity(this, BindPhoneActivity.class);
            return;
        }
        try {
            String type = (String) selectedType.getTag();
            Integer src = null;
            Integer target = null;
            if (type.equals("zfb")) {
                if (App.userInfo.getZfbAccount() == null || App.userInfo.getZfbAccount().equals("")) {
//                    ZxToast.showINFOBottomToast("请先绑定支付宝账号哦！");
//                    BindAliDialog bindAliDialog = new BindAliDialog(getActivity());
//                    bindAliDialog.show();
                    ZxActivityTool.skipActivity(this, V2BindAliPayActivity.class);
                    return;
                }
                target = 11;

            } else if (type.equals("wx")) {
                if (TextUtils.isEmpty(App.userInfo.getWxOpenId())) {
                    BindWxDialog bindWxDialog = new BindWxDialog(getActivity());
                    bindWxDialog.show();
                    return;
                }
                if (TextUtils.isEmpty(App.userInfo.getRealName())) {
//                    CommonDialogCollect.showVerified(this, map -> {
//                        loadingDialog.show();
//                        presenter.updateIdentityInfo(map.get("name"), map.get("idCard"));
//                    });
                    ZxActivityTool.skipActivity(this, V2BindRealNameActivity.class);
                    return;
                }
                target = 10;
            }
            src = this.type;
            presenter.withdrawal(src, target, new BigDecimal(money_et.getText().toString()));
        } catch (Exception e) {
            ZxToast.showBottomToastLight("出现了异常~~");
        }

    }

    private boolean verifyZfb(String text) {
        //如果符合手机号正则，则验证通过
        if (ZxDataTool.isMobile(text)) {
            return true;
        }
        //如果有@符号，则验证通过
        if (text.contains("@")) {
            return true;
        }
        return false;
    }

    @Override
    public void onWait() {
        loadingDialog.show();
    }

    @Override
    public void onSuccess(Order data) {
        loadingDialog.cancel();
        money_et.setText("");
        ZxToast.showSuccessCenterToast("提现成功,请注意在相应账户查收哦~");
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
    }

    @Override
    public void onDisplay(boolean alipay, boolean wechat) {
        content_layout.setVisibility(View.VISIBLE);
        loading_view.setVisibility(View.GONE);
        wx_layout.setVisibility(wechat ? View.VISIBLE : View.GONE);
        zfb_layout.setVisibility(alipay ? View.VISIBLE : View.GONE);
        if (!alipay) {
            selectedType = rootView.findViewWithTag("wx");
            onSelectedType(selectedType);
        }
    }

    @Override
    public void onZfbChangeSuccess() {
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
        loadingDialog.cancel();
        ZxToast.showSuccessBottomToast("支付宝账号更改成功！");
    }

    @Override
    public void onBindNameSuccess() {
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
        loadingDialog.cancel();
        ZxToast.showSuccessBottomToast("身份信息绑定成功！");
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        loading_view.setVisibility(View.GONE);
        if (code == -2)
            ZxToast.showFAILCenterToast("提现失败:" + msg);
        else if (code == -3)
            ZxToast.showFAILCenterToast("更改失败:" + msg);
        else
            ZxToast.showFAILCenterToast(msg);

    }
}
